<?php 

class Articles extends CI_Model {

/*
    var $idarticle   = '';
    var $title   = '';
    var $abstract   = '';
    var $content = '';
    var $idstory    = 0;
    var $iduser    = 0;
    var $idorganization    = 0;
    var $timepublished;
    //var $timestamp;
    var $score = 0;
*/
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    function get_ten_random_entries()
    {
        $this->db->order_by("RAND()", "desc"); 
        $query = $this->db->get('articles', 10);
        return $query->result();
    }
    function get_random_entry()
    {
        $this->db->order_by("RAND()", "desc"); 
        $query = $this->db->get('articles', 1);
        return $query->result();
    }
    
    function search_articles($criteria, $limit, $offset)
    {
        $res = $this->db->like('title', $criteria)
                    ->or_like('abstract', $criteria)
                    ->get('articles', $limit, $offset)->result();
        return $res;         
    }
    
    function find_entry($idarticle)
    {
		$this->db->flush_cache();
		$query = $this->db->get_where('articles', 'idarticle = ' . $idarticle);
        $temp = $query->result();
		return $temp[0];
    }
	function get_articles_for_target_by_name($target_name, $count_limit = 10)
	{
		$target = $this->targets->load_target_by_name($target_name);
		
		return $this->get_articles_for_target($target->locations, $target->tags, '', $count_limit);
	}
    function get_articles_for_target_by_id($id, $count_limit = 10)
	{
		$target = $this->targets->load_target_by_id($id);
		
		return $this->get_articles_for_target($target->locations, $target->tags, '', $count_limit);
	}
	
	function get_articles_for_target($locations, $tags, $keywords, $count_limit = 10)
	{
		return search_articles_for_target($locations, $tags, $keywords, $count_limit);
	}

	function get_users_articles($user)
	{
		$query = $this->db->get_where('articles', 'iduser = ' . $user->iduser);
		return $query->result();
	}
	
	function load_locations($article)
	{
		$query = $this->db->select("geo_location.*")
						->from('articles_geostamps')
						->join('geo_location', 'articles_geostamps.geonameid = geo_location.geonameid')
						->where('idarticle', $article->idarticle)
						/*->order_by('priority')*/
						->get();
        
        return $query->result();
	}

	function load_tags($article)
	{
		$query = $this->db->select("tags.*")
						->from('articles_tags')
						->join('tags', 'articles_tags.idtags = tags.idtags')
						->where('idarticle', $article->idarticle)
						/*->order_by('priority')*/
						->get();
        
        return $query->result();
	}

    function insert_entry()
    {
        $this->timepublished    = time();
        $this->db->insert('articles', $this);
    }
    function update_entry()
    {
        $this->db->update('articles', $this, array('id' => $_POST['id']));
    }
	
	function vote_up($articleID)
	{
		$this->db->set('score', 'score+1',FALSE);
		$this->db->where('idarticle',$articleID); 
		$this->db->update('articles');  		
		return true;
	}
	
	function mark_article_flag_action($article_id, $flag_id, $flag_type, $description, $flag_event_type)
	{
		if($this->session->current_user_name()===FALSE)
		{
			$point_field = "event_value_anon";
			$flagger = null;
			$flagger_id = 0;
		}
		else
		{
			$point_field = "event_value_user";
			$flagger = $this->session->current_user();
			$flagger_id = $flagger->iduser;
		}
		
		//Make sure this is not null
		if(!$flagger_id)
		{
			$flagger_id = 0;
		}
	
		if($description)
		{
			$point_field .= "_desc";
		}
		else
		{
			$description = '';
		}
	
		//Get current points to reduce or add
		$flag_event_type = $this->flags->get_flag_event_type_data($flag_event_type);
		
		//alter the number of points
		$points_to_add = $flag_event_type->$point_field;		
		
		if($flag_id >= 1)
		{
			$this->db->set('points', 'points + '.$points_to_add, FALSE)
					 ->where('idflag',$flag_id)
					 ->update('flag');
					 
			$res = $this->db->select('idflag')->select('points')->select('idflag_type')
				->where('idflag', $flag_id)
				->from('flag')
				->get()->result();
			
			$flag_type = $res[0]->idflag_type;
		}
		else
		{
			//Note: MySQL specific code!
			$res = $this->db->query('INSERT INTO flag (idarticle,iduser_flagger,idflag_type,points) ' .
							 'VALUES ('.$this->db->escape($article_id).','.
										$this->db->escape($flagger_id).','.
										$this->db->escape($flag_type).','.
										$this->db->escape($points_to_add).');');
							 
			$res = $this->db->select('idflag')->select('points')
				->where('idarticle', $article_id)
				->where('idflag_type', $flag_type)
				->from('flag')
				->get()->result();
				
			$flag_id = $res[0]->idflag;
		}

		if($res[0]->points<0)
		{
			$points_to_add -= $res[0]->points;
			
			$this->db->set('points', 0)
					 ->where('idflag',$flag_id)
					 ->update('flag');
		}
		
		//insert flag event
        $this->db->set('idflag', $flag_id)
				 ->set('idflag_event_type', $flag_event_type->idflag_event_type)
				 ->set('timestamp', 'now()', false)
				 ->set('comment', $description)
				 ->set('point_change', $points_to_add)
				 ->insert('flag_event');
				 
		//increase points in articles_flag_points
		$res = $this->db->query('INSERT INTO articles_flag_points (idarticle,idflag_type,points) ' .
						 'VALUES ('.$this->db->escape($article_id).','.
						            $this->db->escape($flag_type).','.
									$this->db->escape($points_to_add).') ' .
						 'ON DUPLICATE KEY UPDATE points=points + '.$points_to_add.';');
						 
		//update the state of the flag
		if($flag_event_type->idflag_states_after > 0)
		{
			$this->db->set('idflag_states', $flag_event_type->idflag_states_after)
			 ->where('idflag',$flag_id)
			 ->update('flag');
		}
		
		return true;
	}
	
	function get_flags_for_article($article)
	{
		$article->action_pending = FALSE;
	
		$query = $this->db->from('articles_flag_points')
					->join('flag_type', 'articles_flag_points.idflag_type = flag_type.idflag_type')
					->join('flag_article_states', 'articles_flag_points.idflag_article_states = flag_article_states.idflag_article_states')
					->where('idarticle', $article->idarticle)
					->get();
		$flags_points_overview = $query->result();
		
		foreach($flags_points_overview as $flag_type)
		{
			$query = $this->db->from('flag')
						->join('users', 'flag.iduser_flagger = users.iduser')
						->join('flag_states', 'flag.idflag_states = flag_states.idflag_states')
						->where('idarticle', $article->idarticle)
						->where('idflag_type', $flag_type->idflag_type)
						->get();
			$flag_type->flags = $query->result();
			
			foreach($flag_type->flags as $flag_thread)
			{
				$query = $this->db->from('flag_event')
							->join('flag_event_type', 'flag_event.idflag_event_type = flag_event_type.idflag_event_type')
							->where('idflag', $flag_thread->idflag)
							->order_by('idflag_event', "asc")
							->get();
				$flag_thread->events = $query->result();
				
				$flag_thread->latest_event = $flag_thread->events[count($flag_thread->events) - 1];
				
				$query = $this->db->from('flag_event_type')
								->where('idflag_event_type in ('. $flag_thread->next_event_author .')')
								->order_by('order', "asc")
								->get();
				
				$flag_thread->next_actions = $query->result();
				
				if($flag_thread->next_event_author)
				{
					$article->action_pending = TRUE;
				}
			}
		}
        return $flags_points_overview;
	}
	
    function relation_text($relation_id)
    {
        //0 - related, 1- prequel->sequel, 2-oposing view, 3 - background
        switch($relation_id)
        {
            case 1: return "sequel";
            case 2: return "prequel";
            case 3: return "different view";
            case 4: return "background";
        }
        return "";
    }
}